<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-input v-model="queryParams.gender" placeholder="请输入性别" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="queryParams.age" placeholder="请输入年龄" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input v-model="queryParams.idCard" placeholder="请输入身份证号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['health:person:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['health:person:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['health:person:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['health:person:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="personList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="体检人员 ID" align="center" prop="personId" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="gender" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="身份证号" align="center" prop="idCard" />
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="登记人员 ID" align="center" prop="staffId" />
      <el-table-column label="样本 ID" align="center" prop="sampleId" />
      <el-table-column label="结果 ID" align="center" prop="resultId" />
      <el-table-column label="报告 ID" align="center" prop="reportId" />
      <el-table-column label="套餐" align="center">
        <el-table-column label="套餐" align="center">
          <template #default="scope">
            {{ packageIdToName[scope.row.bizpackagePhysicalItemId] || '未知套餐' }}
          </template>
        </el-table-column>
      </el-table-column>
      <!-- <el-table-column label="公司ID" align="center" prop="companyId"  /> -->
      <el-table-column label="行业" align="center">
        <template #default="scope">
          {{ industryOptions[scope.row.industryId] || '未知行业' }}
        </template>
      </el-table-column>
      <el-table-column label="发放 ID" align="center" prop="distId" />
      <el-table-column label="预约时间" align="center" prop="appointmentTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appointmentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          {{ statusOptions[scope.row.status] || '未知状态' }}
        </template>
      </el-table-column>
      <el-table-column label="登记时间" align="center" prop="registerTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采血样本条码" align="center" prop="bloodBarcode" />
      <el-table-column label="采便样本条码" align="center" prop="stoolBarcode" />
      <el-table-column label="是否需要采血" align="center">
        <template #default="scope">
          {{ needOptions[scope.row.needBloodTest] || '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="是否需要采便" align="center">
        <template #default="scope">
          {{ needOptions[scope.row.needStoolTest] || '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="采血状态" align="center">
        <template #default="scope">
          {{ scope.row.bloodStatus === 0 ? '未采集' : (scope.row.bloodStatus === 1 ? '已采集' : '未知状态') }}
        </template>
      </el-table-column>

      <el-table-column label="采便状态" align="center">
        <template #default="scope">
          {{ scope.row.stoolStatus === 0 ? '未采集' : (scope.row.stoolStatus === 1 ? '已采集' : '未知状态') }}
        </template>
      </el-table-column>
      <el-table-column label="初检结果" align="center" prop="chujianResult" />
      <el-table-column label="复检结果" align="center" prop="fujianResult" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['health:person:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['health:person:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改体检人员登记对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="personRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="登记人员" prop="staffId">
          <el-input v-model="form.staffId" placeholder="请输入登记人员 ID" disabled />
        </el-form-item>
        <el-form-item label="样本 ID" prop="sampleId">
          <el-input v-model="form.sampleId" placeholder="请输入样本 ID" disabled />
        </el-form-item>
        <el-form-item label="结果 ID" prop="resultId">
          <el-input v-model="form.resultId" placeholder="请输入结果 ID" disabled />
        </el-form-item>
        <el-form-item label="报告 ID" prop="reportId">
          <el-input v-model="form.reportId" placeholder="请输入报告 ID" disabled />
        </el-form-item>
        <el-form-item label="套餐" prop="bizpackagePhysicalItemId">
          <el-select v-model="form.bizpackagePhysicalItemId" placeholder="请选择体检套餐">
            <el-option v-for="(name, id) in packageIdToName" :key="id" :label="name" :value="id" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="公司ID" prop="companyId">
          <el-input v-model="form.companyId" placeholder="请输入公司ID" />
        </el-form-item> -->
        <el-form-item label="行业" prop="industryId">
          <el-select v-model="form.industryId" placeholder="请选择行业">
            <el-option v-for="(label, value) in industryOptions" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="发放 ID" prop="distId">
          <el-input v-model="form.distId" placeholder="请输入发放 ID" disabled />
        </el-form-item> -->
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker clearable v-model="form.appointmentTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="(label, value) in statusOptions" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="登记时间" prop="registerTime">
          <el-date-picker clearable v-model="form.registerTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择登记时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="采血条码" prop="bloodBarcode">
          <el-input v-model="form.bloodBarcode" placeholder="您不需要采血" disabled />
        </el-form-item>
        <el-form-item label="采便条码" prop="stoolBarcode">
          <el-input v-model="form.stoolBarcode" placeholder="您不需要采便" disabled />
        </el-form-item>
        <el-form-item label="是否采血" prop="needBloodTest">
          <el-select v-model="form.needBloodTest" placeholder="请选择">
            <el-option v-for="(label, value) in needOptions" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否采便" prop="needStoolTest">
          <el-select v-model="form.needStoolTest" placeholder="请选择">
            <el-option v-for="(label, value) in needOptions" :key="value" :label="label" :value="value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="初检结果" prop="chujianResult">
          <el-input v-model="form.chujianResult" placeholder="请输入初检结果" />
        </el-form-item>
        <el-form-item label="复检结果" prop="fujianResult">吧 
          <el-input v-model="form.fujianResult" placeholder="请输入复检结果" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Person">
import { listPerson, getPerson, delPerson, addPerson, updatePerson } from "@/api/health/person"
import { listResult, getResult, delResult, addResult, updateResult } from "@/api/health/result"
import { listReport, getReport, delReport, addReport, updateReport } from "@/api/health/report"
import { listPackage, getPackage, delPackage, addPackage, updatePackage } from "@/api/health/package"
import { listIndustry, getIndustry, delIndustry, addIndustry, updateIndustry } from "@/api/health/industry"
import { listCollection, getCollection, delCollection, addCollection, updateCollection } from "@/api/health/collection"
import { listItemPackage, getItemPackage, delItemPackage, addItemPackage, updateItemPackage } from "@/api/health/itemPackage"



const { proxy } = getCurrentInstance()

const personList = ref([])
const packageList = ref([]);
const industryList = ref([])
const itemPackageList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    personId: null,
    name: null,
    gender: null,
    age: null,
    idCard: null,
    phone: null,
    address: null,
    staffId: null,
    sampleId: null,
    resultId: null,
    reportId: null,
    bizpackagePhysicalItemId: null,
    companyId: null,
    industryId: null,
    distId: null,
    appointmentTime: null,
    status: null,
    registerTime: new Date(), // 设置为当前时间
    bloodBarcode: null,
    stoolBarcode: null,
    needBloodTest: null,
    needStoolTest: null,
    bloodStatus: null,
    stoolStatus: null,
    chujianResult: null,
    fujianResult: null
  },
  packageNames: {
    packageId: null,
    packageName: null,
    description: null,
    originalPrice: null,
    discountPrice: null,
  },
  industryNames: {
    industryId: null,
    industryName: null,
    industryModel: null
  },
  packageItems: {
    bizpackagePhysicalItemId: null,
    itemId: null,
    packageId: null
  },
  rules: {
  }
})

const packageIdToName = computed(() => {
  return packageList.value.reduce((acc, item) => {
    acc[item.packageId] = item.packageName;
    return acc;
  }, {});
});

const industryOptions = computed(() => {
  return industryList.value.reduce((acc, item) => {
    acc[item.industryId] = item.industryName;
    return acc;
  }, {});
});
const statusOptions = {
  0: '已取消',
  1: '已预约',
  2: '已完成'
}
const needOptions = {
  0: '不需要',
  1: '需要'
}

const { queryParams, packageNames, industryNames, packageItems, form, rules } = toRefs(data)

/** 查询体检人员登记列表 */
function getList() {
  loading.value = true
  listPerson(queryParams.value).then(response => {
    personList.value = response.rows
    total.value = response.total
    loading.value = false
  });
  listPackage(packageNames.value).then(response => {
    packageList.value = response.rows
    total.value = response.total
    loading.value = false
  });
  listIndustry(industryNames.value).then(response => {
    industryList.value = response.rows
    total.value = response.total
    loading.value = false
  });
  listItemPackage(packageItems.value).then(response => {
    itemPackageList.value = response.rows
    console.log('response.rows:', response.rows);

    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    personId: null,
    name: null,
    gender: null,
    age: null,
    idCard: null,
    phone: null,
    address: null,
    staffId: null,
    sampleId: null,
    resultId: null,
    reportId: null,
    bizpackagePhysicalItemId: null,
    companyId: null,
    industryId: null,
    distId: null,
    appointmentTime: null,
    status: null,
    registerTime: null,
    bloodBarcode: null,
    stoolBarcode: null,
    needBloodTest: null,
    needStoolTest: null,
    bloodStatus: null,
    stoolStatus: null,
    chujianResult: null,
    fujianResult: null
  }
  proxy.resetForm("personRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.personId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function generateBarcode() {
  // 获取当前时间戳（毫秒）
  const timestamp = Date.now().toString();
  // 取最后 6 位时间戳，并确保是6位数字
  let barcode = timestamp.slice(-6);
  return parseInt(barcode, 10);
}
function generateUniqueId() {
  // 获取当前时间戳（毫秒）
  const timestamp = Date.now().toString();
  // 取最后 6 位时间戳 + 2 位随机数（0~99），总共 8 位
  const timePart = timestamp.slice(-6); // 取后 6 位时间戳
  const randomPart = Math.floor(Math.random() * 100).toString().padStart(2, '0');
  return parseInt(timePart + randomPart, 10);
}

// 生成带时间戳的采便和采血条码
const bloodBarcode = generateBarcodeWithTimestamp('BLOOD');
const stoolBarcode = generateBarcodeWithTimestamp('STOOL');
function generateBarcodeWithTimestamp(type) {
  const timestamp = Date.now(); // 获取当前时间戳（毫秒）
  const randomNum = Math.floor(Math.random() * 1000); // 生成0-999之间的随机数
  const combined = (timestamp % 100000000) * 1000 + randomNum; // 组合成最多14位数字
  const barcodeNumber = combined.toString().slice(0, 8); // 截取前8位
  return `${type}${barcodeNumber}`;
}

watch(
  () => [form.value.needBloodTest, form.value.needStoolTest],
  ([newNeedBlood, newNeedStool]) => {
    if (newNeedBlood === '0') {
      form.value.bloodBarcode = null;
    } else if (newNeedBlood === '1') {
      form.value.bloodBarcode = generateBarcodeWithTimestamp('BLOOD');
      form.value.bloodStatus = '0'
    }
    if (newNeedStool === '0') {
      form.value.stoolBarcode = null;
    } else if (newNeedStool === '1') {
      form.value.stoolBarcode = generateBarcodeWithTimestamp('STOOL');
      form.value.stoolStatus = '0'
    }
  },
  { deep: true }
);
function generateTBarcode() {
  // 获取当前时间戳 + 随机数，确保唯一性
  const timestamp = Date.now().toString(); // 当前时间戳（毫秒）
  const randomPart = Math.floor(Math.random() * 1000000).toString().padStart(6, '0'); // 6位随机数

  // 拼接成足够长的数字串，并截取11位
  const combined = (timestamp + randomPart).slice(-11); // 取最后11位

  // 返回 T + 11位数字
  return 'T' + combined;
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  form.value.personId = generateBarcode();
  form.value.sampleId = generateUniqueId(); // 自动生成 sampleId
  form.value.resultId = generateUniqueId();
  form.value.reportId = generateUniqueId();
  form.value.staffId = 104;
  // form.value.distId = generateUniqueId();
  const now = new Date();
  const formattedDate = now.toISOString().slice(0, 10); // 输出 "YYYY-MM-DD"
  form.value.registerTime = formattedDate;

  // form.value.bloodBarcode = generateBarcodeWithTimestamp('BLOOD');
  // form.value.stoolBarcode = generateBarcodeWithTimestamp('STOOL');
  open.value = true
  title.value = "添加体检人员登记"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _personId = row.personId || ids.value
  getPerson(_personId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改体检人员登记"
  })
}

const collectionConfig = {
  '1': {
    '1': '采血室',
    '2': '采便室',
    '3': '检验科'
  },
  '2': {
    '1': '采血室',
    '2': '采便室',
    '3': '检验科',
    '8': '影像科',
    '9': '内镜室',
    '10': '心电图室'
  },
  '3': {
    '1': '采血室',
    '2': '采便室',
    '3': '检验科',
    '4': 'B超室',
    '5': '超声科',
    '6': '实验室',
    '7': '影像科',
    '10': '心电图室'
  },
  '4': {
    '1': '采血室',
    '2': '采便室',
    '3': '检验科',
    '4': 'B超室',
    '5': '超声科',
    '6': '实验室',
    '7': '影像科',
    '8': '放射科',
    '9': '内镜室',
    '10': '心电图室'
  },
  '5': {
    '1': '采血室',
    '2': '采便室',
    '3': '检验科',
    '8': '放射科',
    '9': '内镜室'
  }
};
function handleAddCollections(packageId) {
  const config = collectionConfig[packageId];
  if (!config) return;

  const items = itemPackageList.value.filter(item => item.packageId == packageId);
  if (form.value.needBloodTest == '1') {
    addCollection({
      sampleId: form.value.sampleId,
      personId: form.value.personId,
      sampleType: 11,
      collectionPlace: "采血室",
      barcode: generateBarcodeWithTimestamp('BLOOD'),
      status: 0
    });
  }
  if (form.value.needStoolTest == '1') {
    addCollection({
      sampleId: form.value.sampleId,
      personId: form.value.personId,
      sampleType: 12,
      collectionPlace: "采便室",
      barcode: generateBarcodeWithTimestamp('STOOL'),
      status: 0
    });
  }
  items.forEach(item => {
    const place = config[item.itemId];
    if (place) {
      addCollection({
        sampleId: form.value.sampleId,
        personId: form.value.personId,
        sampleType: item.itemId,
        collectionPlace: place,
        barcode: generateTBarcode(),
        status: 0
      });
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["personRef"].validate(valid => {
    if (valid) {
      if (form.value.personId == null) {
        updatePerson(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPerson({
          personId: form.value.personId,
          name: form.value.name,
          gender: form.value.gender,
          age: form.value.age,
          idCard: form.value.idCard,
          phone: form.value.phone,
          address: form.value.address,
          staffId: form.value.staffId,
          sampleId: form.value.sampleId,
          resultId: form.value.resultId,
          reportId: form.value.reportId,
          bizpackagePhysicalItemId: form.value.bizpackagePhysicalItemId,
          companyId: form.value.companyId,
          industryId: form.value.industryId,
          distId: form.value.distId,
          appointmentTime: form.value.appointmentTime,
          status: form.value.status,
          registerTime: form.value.registerTime,
          bloodBarcode: form.value.bloodBarcode,
          stoolBarcode: form.value.stoolBarcode,
          needBloodTest: form.value.needBloodTest,
          needStoolTest: form.value.needStoolTest,
          bloodStatus: form.value.bloodStatus,
          stoolStatus: form.value.stoolStatus,
          chujianResult: form.value.chujianResult,
          fujianResult: form.value.fujianResult
        }).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          addResult({
            resultId: form.value.resultId,
            itemId: form.value.bizpackagePhysicalItemId,
            personId: form.value.personId
          })
          addReport({
            reportId: form.value.reportId,
            personId: form.value.personId
          })
          handleAddCollections(form.value.bizpackagePhysicalItemId)
            .then(response => {
              open.value = false;
              getList(); // 如果需要的话重新加载数据
            });
        });
      }
    }
  });
}


/** 删除按钮操作 */
function handleDelete(row) {
  const _personIds = row.personId || ids.value
  proxy.$modal.confirm('是否确认删除体检人员登记编号为"' + _personIds + '"的数据项？').then(function () {
    return delPerson(_personIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('health/person/export', {
    ...queryParams.value
  }, `person_${new Date().getTime()}.xlsx`)
}

getList()
</script>
